<template>
  <div id="emrStandardTaskDiv">
    <Breadcrumb content="标准关联任务模板维护" />
    <div class="bodyContent">
      <Splitpanes>
        <Pane size="20">
          <vxe-toolbar perfect>
            <template #buttons>
              <!-- <div class="smallToolTitle">仪器</div>
              <vxe-select v-model="searchForm.instrIds" multiple :filterable="true" clearable @change="valueChangeEvent">
                <vxe-option v-for="instr in instrList" :key="instr.id" :value="instr.id" :label="instr.instrName"></vxe-option>
              </vxe-select> -->
              <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="treeloading" @click="findEmrItemStandardTree"></vxe-button>
            </template>
          </vxe-toolbar>
          <el-scrollbar style="height: calc(100% - 40px)">
            <div class="sampleType">
              <el-scrollbar>
                <el-tree :expand-on-click-node="false" :default-expand-all="true" :data="emrStandardTree" :props="defaultProps" node-key="id" ref="emrTreeRef" highlight-current class="tools-tree" @node-click="handleClickType" v-loading="treeloading">
                  <template #default="{ data, node }">
                    <div style="float: right">
                      <!-- <img :src="`${getAssetsFile('images/qc/' + data.type + '.png')}`" style="width: 15px; height: 15px; margin-right: 10px" /> -->
                      {{ data.name }}
                    </div>
                  </template>
                </el-tree>
              </el-scrollbar>
            </div>
          </el-scrollbar>
        </Pane>
        <Pane size="30">
          <vxe-toolbar perfect>
            <template #buttons>
              <div class="smallToolTitle">任务模板维护</div>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="qloading" :disabled="disabledTag" @click="findItemStandardTaskList"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新增" :disabled="disabledTag" @click="addStandardTaskDailog"></vxe-button>
              <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" :disabled="disabledTag" @click="handleStandardTaskDelete"></vxe-button>
            </template>
          </vxe-toolbar>

          <div class="tableBody">
            <vxe-table ref="standardTaskTableRef" class="mytable-scrollbar" border="inner" align="center" height="auto" :data="standardTaskList" :loading="qloading" @current-change="standardTaskRowClick" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
              <vxe-column type="checkbox" width="30px" align="center"></vxe-column>
              <vxe-column field="taskName" title="标题" width="100"> </vxe-column>
              <vxe-column field="taskContent" title="内容"> </vxe-column>
            </vxe-table>
          </div>
        </Pane>
        <Pane size="50">
          <vxe-toolbar perfect>
            <template #buttons>
              <div class="toolbartitle">模板详情</div>
              <div class="saveBtn">
                <vxe-button type="text" class="button-blue" @click="saveStandardTask('taskFormRef')" icon="vxe-icon-save" :disabled="disabledTag" content="保存"></vxe-button>
              </div>
            </template>
          </vxe-toolbar>
          <el-form ref="taskFormRef" :model="standardTaskForm" :rules="standardTaskFormRule" label-width="100px" inline-message v-loading="qloading">
            <el-row>
              <el-col :span="20">
                <el-form-item prop="taskName" label="任务标题">
                  <el-input type="text" v-model="standardTaskForm.taskName" placeholder="请输入任务标题"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="20">
                <el-form-item prop="taskContent" label="内容">
                  <el-input type="textarea" v-model="standardTaskForm.taskContent" placeholder="请输入任务内容"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div style="height: calc(100% - 150px)" v-show="!IsEmpty(standardTaskForm.id)">
            <OnlyOfficeWord ref="onlyOfficeWordRef" @savedOnlyOffice="savedOnlyOffice"></OnlyOfficeWord>
          </div>
        </Pane>
      </Splitpanes>
    </div>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import moment from 'moment';
import { Splitpanes, Pane } from 'splitpanes';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示框
import { DateToString, formatDateTime, getAssetsFile } from '@/utils/common';
import { AppStore } from '@/stores/store';
import OnlyOfficeWord from '@/components/OnlyOfficeWord.vue';

// 全局变量定义区 ==========
let store = AppStore();
let treeloading = ref(false);
let qloading = ref(false);
let onlyOfficeWordRef: any = ref(null); //检验记录下方的输入模板

let emrStandardTree: any = reactive([]);
let standardTaskList: any = reactive([]); //最左侧质控靶值设定树数据

let { proxy }: any = getCurrentInstance();
// 最左侧的树
let defaultProps = {
  children: 'children',
  label: 'name'
};
let sltStandard: any = {};
let sltTask: any = {};
let disabledTag = ref(true);

let standardTaskForm = reactive({
  id: null,
  taskCode: '',
  taskName: '',
  taskContent: '',
  versionCode: '',
  roleCode: '',
  itemCode: '',
  gradeCode: '',
  standardCode: '',
  seq: 1,
  orgId: ''
});
let contHeight = ref(0); // 获取屏幕高度

// 方法定义区 =============
// 页面加载时更新
onMounted(() => {
  contHeight.value = document.documentElement.clientHeight;
  findEmrItemStandardTree(); // 获取最左侧质控靶值树数据
});

// 获取最左侧质控靶值树 刷新
function findEmrItemStandardTree() {
  treeloading.value = true;
  emrStandardTree.length = 0; //放入数据前清空数据
  const url = '/lis/emr/itemStandardTask/findEmrItemStandardTree';
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: {} })
    .then((res: any) => {
      if (!IsEmpty(res.data)) {
        emrStandardTree.push(...res.data);
        if (emrStandardTree.length > 0) {
          const sltObj = getChildren(emrStandardTree[0]);
          setCurTypeNode(sltObj.id);
          if (sltObj.type == 'emrItemStandard') {
            sltStandard = sltObj;
          } else {
            sltStandard = {};
          }
        } else {
          sltStandard = {};
        }
      }

      //如果点击的当前行数据是父级，那就禁用质控品维护的按钮
      if (!sltStandard.id) {
        disabledTag.value = true;
      } else {
        //如果点击的当前行数据是子集，那就不需要禁用质控品维护的按钮
        disabledTag.value = false;
        findItemStandardTaskList();
      }
      treeloading.value = false;
    })
    .catch((err: any) => {
      treeloading.value = false;
      VxeMessage('获取最左侧质控靶值树异常', VxeNotifyType.error);
    });
}

function findItemStandardTaskList() {
  const el: any = proxy.$refs['taskFormRef'];
  //移除校验结果
  el.clearValidate();
  if (IsEmpty(sltStandard)) {
    VxeMessage('请选择评价标准', VxeNotifyType.error);
  } else {
    qloading.value = true;
    standardTaskList.length = 0; //放入数据前清空数据
    const url = '/lis/emr/itemStandardTask/findItemStandardTaskList';
    proxy.$http
      //注意此处的数据条数
      .get(url, {
        params: {
          versionCode: sltStandard.versionCode,
          roleCode: sltStandard.roleCode,
          itemCode: sltStandard.itemCode,
          standardCode: sltStandard.standardCode
        }
      })
      .then((res: any) => {
        standardTaskList.push(...res.data);
        if (standardTaskList.length == 0) {
          clearStandardTaskForm();
          standardTaskForm.versionCode = sltStandard.versionCode;
          standardTaskForm.roleCode = sltStandard.roleCode;
          standardTaskForm.itemCode = sltStandard.itemCode;
          standardTaskForm.standardCode = sltStandard.standardCode;
          standardTaskForm.gradeCode = sltStandard.gradeCode;
          sltTask = {};
        } else {
          let idx = 0;
          if (IsEmpty(sltTask.id)) {
            idx = 0;
          } else {
            const mids = standardTaskList.map((p: any) => p.id);
            const index = mids.findIndex((p: any) => p == sltTask.id);
            if (index > -1) {
              idx = index;
            } else {
              idx = 0;
            }
          }
          standardTaskRowClick({ row: standardTaskList[idx] }); //默认选中第一条数据
        }
        qloading.value = false;
      })
      .catch((err: any) => {
        qloading.value = false;
        // VxeMessage('获取获取当前字典的字段列表失败',VxeNotifyType.error)
      });
  }
}

// 点击质控品维护表格当前行触发右侧表单变化
function standardTaskRowClick({ row }: any) {
  if (IsEmpty(row)) {
    clearStandardTaskForm();
    sltTask = {};
  } else {
    (proxy.$refs.standardTaskTableRef as any).setCurrentRow(row);
    setStandardTaskForm(row);
    sltTask = row;

    findItemStandardTaskFileList();
  }
}

function findItemStandardTaskFileList() {
  console.log(sltTask);
  const url = '/lis/emr/itemStandardTaskFile/findItemStandardTaskFileList';
  proxy.$http
    .get(url, {
      params: {
        taskId: sltTask.id
      }
    })
    .then(async (res: any) => {
      console.log(res.data);
      let ofObj: any = {};
      if (!IsEmpty(res.data) && res.data) {
        ofObj = {
          id: res.data.id,
          taskId: res.data.taskId,
          title: res.data.fileName,
          fileUrl: res.data.fileUrl,
          orgId: store.userInfo.orgId,
          height: contHeight.value - 80 + 'px',
          isEdit: true
        };
      } else {
        ofObj = {
          id: '',
          taskId: sltTask.id,
          orgId: store.userInfo.orgId,
          title: '',
          fileUrl: 'wordFile/emr/empty.docx',
          height: contHeight.value - 80 + 'px',
          isEdit: true
        };
      }
      onlyOfficeWordRef.value?.inintOfficeConfig(ofObj);
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}

function setStandardTaskForm(row: any) {
  Object.assign(standardTaskForm, row);
}
//点击左侧分类
function handleClickType(obj: any) {
  const type: any = obj.type;
  if (type == 'emrItemStandard') {
    sltStandard = obj;
  } else {
    sltStandard = {};
    clearStandardTaskForm();
    standardTaskList.length = 0;
  }

  //如果点击的当前行数据是父级，那就禁用质控品维护的按钮
  if (!sltStandard.id) {
    disabledTag.value = true;
  } else {
    //如果点击的当前行数据是子集，那就不需要禁用质控品维护的按钮
    disabledTag.value = false;
    findItemStandardTaskList();
  }
}

// 表单校验
let standardTaskFormRule = {
  taskName: [
    {
      required: true,
      message: '请输入任务标题',
      trigger: 'blur'
    }
  ]
};

function saveStandardTask(formName: any) {
  if (IsEmpty(sltStandard)) {
    VxeMessage('请选择评价标准', VxeNotifyType.error);
  } else {
    let $el = proxy.$refs[formName];
    $el.validate((valid: any) => {
      if (!valid) {
        return false;
      }
      if (standardTaskForm.id === null) {
        const url = '/lis/emr/itemStandardTask/addStandardTask';
        const obj: any = {};
        Object.assign(obj, standardTaskForm);
        proxy.$http
          .post(url, obj)
          .then((res: any) => {
            VxeMessage('新增成功', VxeNotifyType.success);
            clearStandardTaskForm();
            sltStandard = res.data;
            findItemStandardTaskList();
          })
          .catch((err: any) => {
            VxeMessage('新增失败', VxeNotifyType.error);
          });
      } else {
        // 修改
        const url = '/lis/emr/itemStandardTask/editStandardTask';
        const obj: any = {};
        Object.assign(obj, standardTaskForm);
        proxy.$http
          .post(url, obj)
          .then((res: any) => {
            VxeMessage('修改成功', VxeNotifyType.success);
            setTimeout(() => {
              clearStandardTaskForm();
              findItemStandardTaskList();
            }, 500);
          })
          .catch((err: any) => {
            VxeMessage('修改失败', VxeNotifyType.success);
          });
      }
    });
  }
}

// 中间质控品维护添加
function addStandardTaskDailog() {
  if (IsEmpty(sltStandard)) {
    VxeMessage('请选择评价标准', VxeNotifyType.error);
  } else {
    clearStandardTaskForm();
    sltTask = {};
    standardTaskForm.versionCode = sltStandard.versionCode;
    standardTaskForm.roleCode = sltStandard.roleCode;
    standardTaskForm.itemCode = sltStandard.itemCode;
    standardTaskForm.standardCode = sltStandard.standardCode;
    standardTaskForm.gradeCode = sltStandard.gradeCode;
    if (standardTaskList && standardTaskList.length > 0) {
      standardTaskForm.seq = Math.max(...standardTaskList.map((item) => item.seq)) + 1;
    } else {
      standardTaskForm.seq = 1;
    }
    (proxy.$refs.standardTaskTableRef as any).clearCurrentRow();
  }
}

function handleStandardTaskDelete() {
  const sltStandardTasks = (proxy.$refs.standardTaskTableRef as any).getCheckboxRecords();
  if (!(sltStandardTasks.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        const data = { emrItemStandardTaskList: sltStandardTasks };
        const url = '/lis/emr/itemStandardTask/batchDeleteItemStandardTask';
        proxy.$http
          .post(url, data)
          .then((res: any) => {
            findItemStandardTaskList(); // 获取检验仪器表格数据
            VxeMessage(res.status.msg, VxeNotifyType.success);
          })
          .catch((err: any) => {
            VxeMessage(err, VxeNotifyType.error);
          });
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  }
}

// 清空表单
function clearStandardTaskForm() {
  standardTaskForm.id = null;
  standardTaskForm.taskCode = '';
  standardTaskForm.taskName = '';
  standardTaskForm.taskContent = '';
  standardTaskForm.versionCode = '';
  standardTaskForm.roleCode = '';
  standardTaskForm.itemCode = '';
  standardTaskForm.gradeCode = '';
  standardTaskForm.standardCode = '';
  standardTaskForm.orgId = '';
  standardTaskForm.seq = 1;

  const el: any = proxy.$refs['taskFormRef'];
  //移除校验结果
  el.clearValidate();
}

function getChildren(obj: any) {
  const children = obj.children;
  if (!IsEmpty(children) && children.length > 0) {
    return getChildren(children[0]);
  } else {
    return obj;
  }
}

function setCurTypeNode(nodeId: any) {
  proxy.$nextTick(() => {
    const treeName = 'emrTreeRef';
    const tree: any = proxy.$refs[treeName];
    tree.setCurrentKey(nodeId);
  });
}
function IsEmpty(value: any) {
  if (value === undefined || value === '' || value === null) {
    return true;
  }
  if (JSON.stringify(value) === '{}') {
    return true;
  }
  return false;
}

//保存word文档
async function savedOnlyOffice(config: any) {
  /*  const data = {
    id: config.id,
    fileName: config.title,
    filePath: '/upload/tender/' + this.docForm.tenderId + '/' + config.id + '.docx'
  };
  this.axios
    .post('/api/tender/editTenderDocItem', data)
    .then(async (res: any) => {
      if (res.status.code !== 1) {
        VxeMessage('保存失败：' + res.status.msg, VxeNotifyType.error);

        //修改编辑状态
        this.axios.post('/api/tender/editTenderDoc', { id: this.curDocCata.id, status: 1 });
        this.curDocCata.status = 1;
      }
    })
    .catch((err) => {
      VxeMessage('保存错误：' + err, VxeNotifyType.error);
    });*/
}
</script>

<style lang="scss" scoped>
#emrStandardTaskDiv {
  height: 100%;
  .bodyContent {
    height: calc(100% - 60px);
    .splitpanes {
      background-color: $base-white;
      // 显示过期的质控品按钮
      .saveBtn {
        float: left;
        margin: 0px 0px 0px 600px;
      }

      // 附加按钮间距
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }
      // 最右侧质控靶值设定表格
      .tableBody {
        height: calc(100% - 40px);
      }
    }

    :deep(.result-table) {
      .number-right .vxe-cell {
        text-align: right;
        span {
          display: inline-block;
          width: calc(100% - 12px);
          div {
            display: inline-block;
            background-color: #ebe9e9;
            width: calc(100% - 80px);
          }
        }
      }
      .el-icon-warning {
        color: red;
      }
      .el-icon-warning-outline {
        color: $warning-color;
      }
      .el-icon-success {
        color: $success-color;
      }
      .zS2 {
        color: $warning-color;
      }
      .zS3 {
        color: $danger-color;
      }
      .zS-2 {
        color: $brand-color;
      }
      .zS-3 {
        color: #6600ff;
      }
    }
  }

  :deep(.drawerBulkModal) {
    inset: 50px 0 0 70px !important;
  }
  :deep(.el-drawer__body) {
    .iqcOutControl {
      width: 800px;
      // margin: 0 auto;
      transform: translateX(65%);
    }
  }
}
</style>
